import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCDemo2 {
    public static void main(String[] args) throws SQLException {
        //1.创建数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java111?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("1115");

        //2.建立链接
        Connection connection = dataSource.getConnection();

        //3.构造SQL
        String sql = "select * from test";
        PreparedStatement statement = connection.prepareStatement(sql);

        //4.执行 sql
        ResultSet resultSet = statement.executeQuery();//其他操作一样，这里不一样,结果是表格

        //5. 遍历结果集合
        while (resultSet.next()) {
            //针对这里的光标指向的行进行处理.
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            System.out.println("id= " + id + "name= " + name);
        }

        //6.释放资源
        statement.close();
        connection.close();
    }
}
